package com.sgb.kjwl.view.ui.activity.packers;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.aspectj.login.LoginCheck;
import com.sgb.kjwl.databinding.ActivityLaborServiceAndEmploymentDetailBinding;
import com.sgb.kjwl.model.entity.packers.LaborWorkMomentDetailEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.utils.WebJsConstants;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.viewmodel.packers.LaborServiceAndEmploymentDetailViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.ycbjie.webviewlib.base.X5WebChromeClient;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : younghow
 * @date : 2021/7/8 17:13
 * @desc :劳务用工详情页
 */
public class LaborServiceAndEmploymentDetailActivity extends AppActivity {

    ActivityLaborServiceAndEmploymentDetailBinding mBinding;
    LaborServiceAndEmploymentDetailViewModel mViewModel;
    private X5WebChromeClient chromeClient;
    private boolean mIsFollow = false;
    private String no;
    private String mWorkNo;
    private String mWorkName;
    private String mMomentNo;
    private String mWorkNameForList;
    private String mUserNo;
    private String imId;
    private boolean success;
    private int employmentType;
    private boolean mDefaultIsApply;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setOnBackClickListener(v -> onBackPressed());
    }

    @Override
    protected void initView() {
        super.initView();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_labor_service_and_employment_detail);
        mBinding.setLifecycleOwner(this);
        mViewModel = new ViewModelProvider(this).get(LaborServiceAndEmploymentDetailViewModel.class);

        no = getIntent().getStringExtra("no");
        mWorkNo = getIntent().getStringExtra("workNo");
        mWorkName = getIntent().getStringExtra("workName");
        mMomentNo = getIntent().getStringExtra("mMomentNo");
        employmentType = getIntent().getIntExtra("employmentType", 0);
        imId = getIntent().getStringExtra("imId");

        if (mMomentNo == null) {
            mMomentNo = "";
        }

        mWorkNameForList = getIntent().getStringExtra("workNameForList");

        mBinding.wvLaborService.registerHandler(WebJsConstants.GO_TO_CALL_PHONE, (data, function) -> {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
            } else {
                if (mMomentNo != null && mMomentNo.equals(mUserNo)) {
                    MToast.showToast(this, "不能拨打自己的电话");
                } else {
                    com.sgb.kjwl.utils.DialogHelper.showDialog(getActivity(), "确认呼叫", jsonChange(data), "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            ActivityJump.jumpToPhone(LaborServiceAndEmploymentDetailActivity.this, jsonChange(data));
                        }
                    });
                }
            }
        });
        initLiveData();
        initData();
        initButton();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUserNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
    }

    private void initButton() {
        mBinding.btnApply.setOnClickListener(this);
        mBinding.linAttention.setOnClickListener(this);
        mBinding.linIm.setOnClickListener(this);
        mBinding.linHanxun.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.btn_apply) {
            disabledView(v);
            apply();
        } else if (id == R.id.lin_im) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(getActivity(), false);
            } else {
                if (employmentType == 0) {
                    MToast.showToast(this, "该信息为个人用户发布，当前无法交流");
                    return;
                }

                if (mMomentNo.equals(mUserNo)) {
                    MToast.showToast(this, "不能和自己交流");
                } else {
                    if (!TextUtils.isEmpty(imId)) {
                        mViewModel.findCustomerServiceImAccount(imId);
                    } else {
                        MToast.showToast(LaborServiceAndEmploymentDetailActivity.this, "未设置客服人员，无法交流！");
                    }
                }
            }
        } else if (id == R.id.lin_hanxun) {
            sendNote();
        } else if (id == R.id.lin_attention) {
            followCheck();
        }
    }

    private void initLiveData() {
        mViewModel.loadingLiveData.observe(this, aBoolean -> DialogHelper.showProgressDialog(LaborServiceAndEmploymentDetailActivity.this, null, "数据加载中...", 0, false,true, null).setCanceledOnTouchOutside(false));
        mViewModel.successLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());
        mViewModel.errorLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());

        mViewModel.mUrlLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                mBinding.wvLaborService.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                mBinding.wvLaborService.getSettings().setDomStorageEnabled(true);
                mBinding.wvLaborService.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
                mBinding.wvLaborService.getSettings().setAppCacheEnabled(true);
                chromeClient = new X5WebChromeClient(mBinding.wvLaborService, LaborServiceAndEmploymentDetailActivity.this) {
                    @Override
                    public void onProgressChanged(WebView view, int newProgress) {
                        super.onProgressChanged(view, newProgress);
                        Log.e("WebViewX5Activity", newProgress + "");
                    }
                };
                mBinding.wvLaborService.setWebChromeClient(chromeClient);
                mBinding.wvLaborService.loadUrl(s);
            }
        });

        mViewModel.mSignUpSuccessLiveData.observe(this, aBoolean -> {
            success = true;
            mDefaultIsApply=true;
            mBinding.btnApply.setBackgroundResource(R.drawable.shape_btn_apply_frame_build_checked_detail);
            mBinding.btnApply.setText("已报名");
        });

        mViewModel.mFollowSuccessLiveData.observe(this, aBoolean -> {
            success = true;
            if (!mIsFollow) {
                mBinding.ivAttention.setImageResource(R.mipmap.gz_orange_no_select);
                mBinding.tvAttention.setTextColor(ContextCompat.getColor(LaborServiceAndEmploymentDetailActivity.this, R.color.color_666666));
                mBinding.tvAttention.setText("关注");
            } else {
                mBinding.ivAttention.setImageResource(R.mipmap.gz_orange);
                mBinding.tvAttention.setTextColor(ContextCompat.getColor(LaborServiceAndEmploymentDetailActivity.this, R.color.color_EF4033));
                mBinding.tvAttention.setText("已关注");
            }
        });

        mViewModel.mCheckIsApplyLiveData.observe(this, signUpCheckEntity -> {
            if (signUpCheckEntity.getNotice() == null) {
                com.sgb.kjwl.utils.DialogHelper.showDialogForTeam(LaborServiceAndEmploymentDetailActivity.this, "请确认报名信息", new String[]{"工种", "姓名", "联系电话"}, new String[]{mWorkNameForList, signUpCheckEntity.getUserName(), signUpCheckEntity.getUserPhone()}, "取消报名", "确认报名", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        Map<String, Object> map = new HashMap<>();
                        map.put("relationNo", no);
                        map.put("workNo", mWorkNo);
                        mViewModel.apply(map);
                    }
                });
            } else {
                MToast.showToast(LaborServiceAndEmploymentDetailActivity.this, signUpCheckEntity.getNotice());
                if (signUpCheckEntity.getNotice().contains("该劳务用工已招满，请重新选择")) {
                    success = true;
                    onBackPressed();
                }
            }
        });

        mViewModel.mLaborDetailLiveData.observe(LaborServiceAndEmploymentDetailActivity.this, new Observer<LaborWorkMomentDetailEntity>() {
            @Override
            public void onChanged(LaborWorkMomentDetailEntity laborWorkMomentDetailEntity) {
                mIsFollow = laborWorkMomentDetailEntity.getIsFocus();
                mDefaultIsApply = laborWorkMomentDetailEntity.getIsApply();

                if (mDefaultIsApply) {
                    mBinding.btnApply.setBackgroundResource(R.drawable.shape_btn_apply_frame_build_checked_detail);
                    mBinding.btnApply.setText("已报名");
                }

                if (!mIsFollow) {
                    mBinding.ivAttention.setImageResource(R.mipmap.img_gary_heart);
                    mBinding.tvAttention.setTextColor(ContextCompat.getColor(LaborServiceAndEmploymentDetailActivity.this, R.color.color_666666));
                    mBinding.tvAttention.setText("关注");
                } else {
                    mBinding.ivAttention.setImageResource(R.mipmap.gz_orange);
                    mBinding.tvAttention.setTextColor(ContextCompat.getColor(LaborServiceAndEmploymentDetailActivity.this, R.color.color_EF4033));
                    mBinding.tvAttention.setText("已关注");
                }
            }
        });

    }

    private void initData() {
        mViewModel.getH5Url(no);
        mViewModel.laborDetail(no);
    }

    @Override
    public void onBackPressed() {
        if (success) {
            Intent intent = new Intent();
            intent.putExtra("isFocus", mIsFollow);
            intent.putExtra("isApply", mDefaultIsApply);
            setResult(2,intent);
            NumberConstant.sIsChangeForTeam = 1;
        }
        super.onBackPressed();
    }

    private String jsonChange(String jsonString) {
        String phone = "";
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            phone = jsonObject.getString("id");
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        return phone;
    }

    public void disabledView(final View v) {
        v.setClickable(false);
        // 延迟5秒，恢复点击事件
        new Handler().postDelayed(() -> v.setClickable(true), 5000);
    }

    @LoginCheck(needRealName = true)
    public void followCheck(){
        if (mMomentNo.equals(mUserNo)) {
            MToast.showToast(this, "不能关注自己发布的信息");
        } else {
            mIsFollow = !mIsFollow;
            mViewModel.followForTeam(no, "6", mIsFollow);
        }
    }

    @LoginCheck(needRealName = true)
    public void sendNote(){
        if (mMomentNo.equals(mUserNo)) {
            MToast.showToast(this, "不能给自己发送函询");
        } else {
            PickInquireByLetterActivity.start(LaborServiceAndEmploymentDetailActivity.this, no, "team", "", "", "3", mWorkName, "laborWorkDetail");
        }
    }

    @LoginCheck(needRealName = true)
    public void apply(){
        if (mMomentNo.equals(mUserNo)) {
            MToast.showToast(this, "自己不能报名自己发布的劳务用工");
        } else {
            if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0){
                mViewModel.signUpTerm(no);
            }else {
                MToast.showToast(this, "个人身份才能报名");
            }
        }
    }
}
